package com.tangyee.person;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tangyee.person.activity.ChangePasswordActivity;
import com.tangyee.person.activity.ChangeUserNameActivity;
import com.tangyee.person.db.PersonInfo;
import com.tangyee.person.view.CircleImageView;
import com.tangyee.person.view.SelectPopupWindow;
import com.tangyee.R;
import com.tangyee.person.activity.ChangePasswordActivity;
import com.tangyee.person.activity.ChangeUserNameActivity;
import com.tangyee.person.db.PersonInfo;
import com.tangyee.person.view.CircleImageView;
import com.tangyee.person.view.SelectPopupWindow;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;
import org.litepal.crud.LitePalSupport;
import org.litepal.tablemanager.Connector;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class HeadPicture extends AppCompatActivity implements View.OnClickListener{
    PersonInfo personInfo;
    private TextView username;
    SelectPopupWindow menuWindow;
    CircleImageView headImageView;
    private Bitmap mBitmap;
    //状态码
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int CAMERA_PREMISSION_CODE = 100;
    private static String path =null;//sd路径
    private static final String PHOTONAME="myhead.jpg";
    private static final int NICKNAME_CODE = 200;
    private static final int CHANGEPASSWD = 300;
    private String mImagePath; //= Environment.getExternalStorageDirectory()+"/meta/";
    private File mCurrentFile;//本地头像文件
    private Uri versionForUri;//android7.0以下版本，我在4.0 6.0下测试
    private final static String authorityPath = "com.tangyee.fileprovider";//根据官网的提示
    // 这个值和AndroidManifest.xml中的文件相关联，
    // 这个String的值和xml中的文件name必须相同,可以取任意值
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_person_headpicture);
        findViewById(R.id.backToperson1).setOnClickListener(this);
        findViewById(R.id.headImage_userinfo_layout).setOnClickListener(this);
        findViewById(R.id.nickname_userinfo_layout).setOnClickListener(this);
        findViewById(R.id.passwd_userinfo_layout).setOnClickListener(this);
        findViewById(R.id.phone_userinfo_layout).setOnClickListener(this);
        headImageView=findViewById(R.id.headimage_userinfo) ;
        username=(TextView) findViewById(R.id.nickname_userinfo);
        personInfo= LitePal.findFirst(PersonInfo.class);
        username.setText(personInfo.getName());
        assignment();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case  R.id.backToperson1:
                finish();
                break;
            case R.id.headImage_userinfo_layout:
                //修改头像
                popChangeWindow(R.id.headImage_userinfo_layout);
                break;
            case R.id.nickname_userinfo_layout:
                //昵称
                Intent intent2 = new Intent(HeadPicture.this,ChangeUserNameActivity.class);
                startActivity(intent2);
                finish();
                break;
            case R.id.passwd_userinfo_layout:
                //密码
                Intent intent1 = new Intent(HeadPicture.this,ChangePasswordActivity.class);
                startActivity(intent1);
                break;
            case R.id.phone_userinfo_layout:
                Toast.makeText(HeadPicture.this, "你点击了手机号码", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    //初始化赋值函数
    private void assignment(){
        path = Environment.getExternalStorageDirectory().getPath();
        mImagePath = Environment.getExternalStorageDirectory().getPath();
        //Log.e("存储相片的地址:mImagePath",mImagePath);
        //Log.e("相片的地址:Path",path);
        if (personInfo.getHeadshot()!=null){
            Bitmap bmp=Bytes2Bitmap(personInfo.getHeadshot());
            headImageView.setImageBitmap(bmp);
        }
    }
    private void popChangeWindow(final int layoutCode){
        //弹出选项
        menuWindow = new SelectPopupWindow(HeadPicture.this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuWindow.dismiss();
                switch (v.getId()) {
                    case R.id.item_popupwindows_frist: {        //点击拍照按钮
                        if(layoutCode==R.id.headImage_userinfo_layout){
                            takePhotos();
                        }
                    }break;
                    case R.id.item_popupwindows_second: {       //点击从相册中选择按钮
                        if(layoutCode==R.id.headImage_userinfo_layout) {
                            choosePhotos();
                        }
                    }break;
                    default:
                        break;
                }
            }
        });
        if(layoutCode==R.id.headImage_userinfo_layout) {
            menuWindow.setTextStyle("拍照","从相册中选取");
        }
        //设置弹窗位置
        menuWindow.showAtLocation(HeadPicture.this.findViewById(R.id.userinfo),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if(resultCode==HeadPicture.RESULT_OK){
            switch (requestCode){
                case TAKE_PICTURE:{
                    //Log.e("TakePhoto","照相后裁剪");
                    if (24 > android.os.Build.VERSION.SDK_INT){
                        //Log.e("andrid7.0以下","vong");
                        cropImage(versionForUri);

                    }else {
                        //Log.e("andrid7.0以上","cnong");
                        cropImage(FileProvider.getUriForFile(HeadPicture.this,
                                authorityPath, mCurrentFile));
                    }
                }break;
                case CHOOSE_PICTURE:{
                    //Log.e("ChoosePhoto","选照后裁剪");
                    cropImage(data.getData()); // 对图片进行裁剪处理
                }break;
                case CROP_SMALL_PICTURE:{
                    if (data != null) {
                        saveImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                }break;
            }
        }
    }
    /**
     * 裁剪图片方法实现
     */
    protected void cropImage(Uri uri) {
        if (null == uri ) {
            //Log.i("alanjet", "The uri is not exist.");
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        //加权
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        //com.android.camera.action.CROP这个action是用来裁剪图片用的
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }
    /**
     * 保存裁剪之后的图片数据
     */
    protected void saveImageToView(Intent data) {
        Bundle extras = data.getExtras();//处理传过来的Intent里的数据
        if (extras != null) {
            mBitmap = extras.getParcelable("data");
            //这里图片是方形的，可以用一个工具类处理成圆形,先不做特效
            headImageView.setImageBitmap(mBitmap);//显示图片
            byte[] headshot= img(mBitmap);
            personInfo.setHeadshot(headshot);
            personInfo.update(1);
            //存到本地
            /**
             *  在这个地方可以写上上传该图片到服务器的代码.现在没有暂时不写
             */
        }
    }
    //权限处理
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CAMERA_PREMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请成功，可以拍照
                takePhotos();
            } else {
                Toast.makeText(HeadPicture.this,
                        "你拒绝了权限，该功能不可用\n可在应用设置里授权拍照哦",Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    private boolean hasSdcard(){
        //判断是否有SD卡
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }else{
            return false;
        }
    }
    private void choosePhotos(){
        //Log.e("Star&hoosePhoto","开始选择照片");
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, null);
        openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
    }
    private void takePhotos(){
        //Log.e("打印android系统版本号",""+ Build.VERSION.SDK_INT);
        //Log.e("Star&TakePhoto","开始拍照片");
        if (ContextCompat.checkSelfPermission(HeadPicture.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(HeadPicture.this,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,}, CAMERA_PREMISSION_CODE);
        }else {
            if (24 > android.os.Build.VERSION.SDK_INT) {
                //系统版本低于android 7.0
                // 激活相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
                try {
                    File photoFile = new File(Environment.getExternalStorageDirectory(), PHOTONAME);
                    try {
                        if (photoFile.exists()){
                            //Log.e("删除文件在 355 行","开始删文件");
                            photoFile.delete();//删除
                        }
                        photoFile.createNewFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    versionForUri = Uri.fromFile(photoFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, versionForUri);
                    startActivityForResult(intent, TAKE_PICTURE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //高于7.0版本的方法
                try {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
                        File path = new File(mImagePath);
                        if (!path.exists()) {
                            path.mkdir();
                        }
                        mCurrentFile = new File(mImagePath, PHOTONAME);//这里已经创建了头像文件，所以其他部分只要读取即可
                        try {
                            if (mCurrentFile.exists()){
                                //Log.e("删除文件在 381 行","开始删文件");
                                mCurrentFile.delete();//删除
                            }
                            mCurrentFile.createNewFile();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Uri uri= FileProvider.getUriForFile(HeadPicture.this,
                                authorityPath, mCurrentFile);
                        //Log.d("UserinfoTakePhoto", "filePath = " + uri.toString());
                        cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                        startActivityForResult(cameraIntent, TAKE_PICTURE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //Log.e("拍照出错了", "TakePhoto");
                }
            }
        }
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("filePath", mImagePath);
        //Log.d("保存时", "onSaveInstanceState");
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (TextUtils.isEmpty(mImagePath)) {
            mImagePath = savedInstanceState.getString("filePath");
        }
        //Log.d("UserRe", "onRestoreInstanceState");
    }
    //图片转二进制
    private byte[] img(Bitmap bitmap){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    //二进制转图片
    public Bitmap Bytes2Bitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }
}
